package com.uilt;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

public class JdbcUtil {
   public static Connection connection =null;

    static {
       try {
           // 2:加载数据库驱动：
           Class.forName("com.mysql.jdbc.Driver");
           //添加数据库的连接
           String url="jdbc:mysql://localhost:3306/lay";
           String name="root";
           String password="123456";
           connection = DriverManager.getConnection(url, name, password);
       }catch (Exception e){
           e.printStackTrace();
       }
    }

    //{"msg":"登陆成功","object":{"id":0,"name":"lisi","password":"123"},"state":200}

    //通用的查询
    public static ResultSet getObject(List<Object> obj, String sql){
        ResultSet resultSet =null;
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < obj.size(); i++) {
                  preparedStatement.setObject((i+1),obj.get(i));
            }
            resultSet=preparedStatement.executeQuery();
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultSet;
    }

    //通用增，删，改
    public static int updateObject(List<Object> obj,String sql){
        int num =-1;
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            for (int i = 0; i < obj.size(); i++) {
                preparedStatement.setObject((i+1),obj.get(i));
            }
            num=preparedStatement.executeUpdate();
        }catch (Exception e){
            e.printStackTrace();
        }
        return num;
    }
}
